from datetime import datetime
from io import BytesIO
import json
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.shortcuts import redirect, render
from reportservice.dbhelper import DBTool
from reportservice.helpers import ApiResponse
from yida_app_service.linanzjz.xm_cloud_config import XmCloudClient
from yida_app_service.utils.common_utils import timestamp_to_yida_date
from .yida_config import YidaClient
from yida_app_service.xu_cloud_client import XmCloudBaseClient
from yida_app_service.views import get_xm_client
import qrcode
import base64
from collections import defaultdict
yida_client = YidaClient()
xm_client = XmCloudClient()
admin_user_id = "014835331124251186"
company_name = "linanzjz"

@csrf_exempt
@require_http_methods(["GET"])
def create_report(request):
    report_code = request.GET.get("report_code")
    report_result = yida_client.get_form_data_by_search_field("FORM-0E7AF60AC4F149388DB1F9BA33387CDD0D87",
                                                                    admin_user_id,
                                                                    search_field=[
                                                                        {
                                                                            "type": "TEXT ",
                                                                            "operator": "eq",
                                                                            "componentName": "TextField ",
                                                                            "key": "textField_lzw5dy5z",
                                                                            "value": report_code
                                                                        }
                                                                    ])
    sample_result = yida_client.get_form_data_by_search_field("FORM-2031FFBD99D1442AA606BB665B218400TTVG",
                                                                    admin_user_id,
                                                                    search_field=[
                                                                        {
                                                                            "type": "TEXT ",
                                                                            "operator": "eq",
                                                                            "componentName": "TextField ",
                                                                            "key": "textField_lzwdkwlk",
                                                                            "value": report_code
                                                                        }
                                                                    ])
    sample_ids = [sample.form_data.get("textField_m0g5ssx7") for sample in sample_result]
    report_form:dict = report_result[0].form_data
    sample_form:dict = sample_result[0].form_data#样品组表单
    sample_result_extra = sample_form.get("multiSelectField_m17ibo5s",[])
    #formatted_items = {item.split('##')[0]: item.split('##')[1] for item in sample_result_extra}
         
    #print(formatted_items)
    wt_inst = json.loads(json.loads(report_form.get("associationFormField_lzw5dy60_id")))
    commission_result = yida_client.get_form_items_by_ids(wt_inst[0].get('formUuid'),wt_inst[0].get("instanceId"),admin_user_id)
    commission_form = commission_result[0].form_data
    public_render_data_item = ["报告编号","工程名称","检测项目","委托人","委托编号","委托单位","委托日期","送检日期","检测类别","生产厂家",
                              "备注","建设单位","委托单位","见证人","样品状态","见证单位","施工单位"
                              ]
    render_data = {
        "结论状态":report_form.get("selectField_lzw5dy65"),
        "报告编号":commission_form.get("textField_lzs0x0b9"),
        "工程名称":commission_form.get("textField_lzuvzaex"),
        "检测项目":commission_form.get("selectField_m0dj9ha3"),
        "委托人":commission_form.get("textField_lzxv9z4b"),
        "委托编号":commission_form.get("textField_lzs0x0b9"),
        "委托单位":commission_form.get("textField_lzs0x0ba"),
        "委托日期":commission_form.get("dateField_lzweua3h"),
        "送检日期":report_form.get("dateField_lzw5dy6a"),
        "检测结束时间":report_form.get("dateField_lzw5dy6b"),
        "检测依据":"《依据一》,《依据二》",
        # "质保单号":formatted_items.get('质保单号'),
        # "备注":formatted_items.get('备注'),
        # "建设单位":formatted_items.get('建设单位'),
        # "委托单位":formatted_items.get('委托单位'),
        # "生产厂家":formatted_items.get('生产厂家'),
        # "见证人":formatted_items.get('见证人'),
        # "样品状态":formatted_items.get('样品状态'),
        # "样品处理方式":formatted_items.get('样品处理方式'),
        # "见证单位":formatted_items.get('见证单位'),
        # "施工单位":formatted_items.get('施工单位'),
    }

    key_count = defaultdict(int)
    for item in sample_result_extra:
        if '##' in item:
            key, value = item.split('##') 
            if key in render_data:
                if key not in public_render_data_item:
                    key_count[key] += 1  # 记录出现次数
                    new_key = f"{key}_{key_count[key]}"  
                    render_data[new_key] = value  
            else:
                render_data[key] = value       
    #print(render_data)
    
    #associationFormField_lzs0x0b3_id associationFormField_lzs0x0am
    #detection_project_inst = json.loads(json.loads(commission_form.get("associationFormField_lzs0x0b3_id")))
    #detection_project_result = yida_client.get_form_items_by_ids(detection_project_inst[0].get('formUuid'),detection_project_inst[0].get("instanceId"),admin_user_id)
    #detection_project_form = detection_project_result[0].form_data
    xm_client = XmCloudClient()
    # print(commission_form.get("selectField_m0dj9ha3_id"))
    model_details = xm_client.get_xm_exam_item_detail(commission_form.get("selectField_m0dj9ha3_id"))
    # print(model_details)
    model_id_resource = model_details["data"]["report_model_id"]
    if not model_id_resource:
        return ApiResponse.fail("该检测项目未配置报告模板")
    create_report_result = xm_client.create_special_report_record(model_ids = model_id_resource,
                                           name=commission_form.get("textField_lzs0x0b9"),
                                           pub_render_data=render_data,
                                           sample_ids=sample_ids)
    if create_report_result.get("code") == 200:
        return ApiResponse.success(create_report_result.get("data"))
    else:
        return ApiResponse.fail(create_report_result.get("message"))
    
@csrf_exempt
@require_http_methods(["POST"])
def gen_serial_number(form_uuid,match_field_data,sn_field):
    try:
        if isinstance(match_field_data,list):
            match_field_data = match_field_data + [{"key":sn_field,"value":"","type":"DOUBLE","operator":"is_not","componentName":"NumberField"}]
        result = yida_client.get_form_data_by_search_field(form_uuid=form_uuid,
                                                  userId=admin_user_id,
                                                  search_field=match_field_data,
                                                  page_size=5,
                                                  dynamic_order={sn_field:"-"})
        if result:
            serial_number = result[0].form_data.get(sn_field,0)+1
            print(serial_number)
            return serial_number
        elif len(result) == 0:
            return 1
    except Exception as err:
        return 0
    
@csrf_exempt
@require_http_methods(["GET"])
def batch_new_sample(request):
    form_inst_id=request.GET.get("form_inst_id")
    #获取样品组信息
    form_uuid = "FORM-2031FFBD99D1442AA606BB665B218400TTVG"
    sample_result = yida_client.get_form_items_by_ids(form_uuid,form_inst_id,admin_user_id)
    if not sample_result:
        return ApiResponse.fail("未找到样品组信息")
    sample_form_data = sample_result[0].form_data
    batch_size = sample_form_data["numberField_lzuzy7z5"]
    for i in range(1,batch_size):
        batch_form_data = {
            **sample_form_data,
            "selectField_m0emrkj8":sample_form_data["selectField_m0emrkj8_id"],
            "selectField_m0dj9ha3":sample_form_data["selectField_m0dj9ha3_id"],
            "selectField_m0dj9ha7":sample_form_data["selectField_m0dj9ha7_id"],
            "employeeField_lzwdkwlm":sample_form_data["employeeField_lzwdkwlm_id"],
            "numberField_lzuzy7z5":1,
            "associationFormField_lzuvjinv":json.loads(json.loads(sample_form_data["associationFormField_lzuvjinv_id"])),
            "numberField_m0g5ssx9":i+1,
        }
        yida_client.create_form_data(form_uuid,admin_user_id,batch_form_data)
    return ApiResponse.success("批量创建成功")

@csrf_exempt
@require_http_methods(["GET"])
def calc_total_amount(request):
    project_id = request.GET.get("project_id")#项目编号
    statement_number = request.GET.get("statement_number")#结算单号
    #获取该项目下委托单详情
    
    project_result_response = yida_client.get_all_form_data_by_search_field("FORM-38C305CFD3D14A8B99984C59FE48E537J8SW",
                                                                    admin_user_id,
                                                                    search_field=[
                                                                        {
                                                                            "type": "TEXT ",
                                                                             "operator": "eq",
                                                                             "componentName": "TextField ",
                                                                             "key": "textField_m0am6qv4",
                                                                             "value": project_id
                                                                        },
                                                                        {
                                                                            "key":"selectField_m0dijv87",
                                                                            "value":"结算中",
                                                                            "type":"ARRAY",
                                                                            "operator":"eq",
                                                                            "componentName":"SelectField"
                                                                        }
                                                                    ])
    if project_result_response == None:
        return ApiResponse.success("暂无委托需要结算")
    project_result,total = project_result_response
    project_all_result = yida_client.get_all_form_data_by_search_field("FORM-38C305CFD3D14A8B99984C59FE48E537J8SW",
                                                                    admin_user_id,
                                                                    search_field=[
                                                                        {
                                                                            "type": "TEXT ",
                                                                             "operator": "eq",
                                                                             "componentName": "TextField ",
                                                                             "key": "textField_m0am6qv4",
                                                                             "value": project_id
                                                                        },
                                                                        {
                                                                            "key":"numberField_m09lw3i6",
                                                                            "value":"",
                                                                            "type":"DOUBLE",
                                                                            "operator":"is_not",
                                                                            "componentName":"NumberField"}
                                                                    ])
    sorted_project_result = sorted(
        project_result,
        key=lambda x: datetime.fromtimestamp(x.form_data['dateField_m0dlhzcw']/1000)
    )
    project_all_result_resource = project_all_result[0]
    total_amount = sum(item.form_data['numberField_m09lw3i6'] for item in project_all_result_resource if 'numberField_m09lw3i6' in item.form_data)#应收款金额
    yida_client.update_form_data_by_field(
                "FORM-2E26102393E0493BA3EC8F1753C3911EYXYD",
                admin_user_id,
                [{
                    "type": "TEXT",
                    "operator": "eq",
                    "componentName": "TextField",
                    "key": "textField_m0eljcmb",
                    "value": project_id
                }],
                {"numberField_lzs6sljt": total_amount}
    )
    statement_information = yida_client.get_all_form_data_by_search_field("FORM-2E26102393E0493BA3EC8F1753C3911EYXYD",
                                                                    admin_user_id,
                                                                    search_field=[
                                                                        {
                                                                            "type": "TEXT ",
                                                                             "operator": "eq",
                                                                             "componentName": "TextField ",
                                                                             "key": "textField_m0eljcmb",
                                                                             "value": project_id
                                                                        }
                                                                    ])#结算单信息详情
    refund_information = yida_client.get_all_form_data_by_search_field("FORM-F53D1354167C4D408B0AEF08793730A8A0G7",
                                                                    admin_user_id,
                                                                    search_field=[
                                                                        {
                                                                            "type": "TEXT ",
                                                                             "operator": "eq",
                                                                             "componentName": "TextField ",
                                                                             "key": "textField_m0eoxsa0",
                                                                             "value": statement_number
                                                                        }
                                                                    ])#回款信息详情
    refund_item = refund_information[0]
    refund_amount = sum(item.form_data['numberField_m0eohh4q'] for item in refund_item  if 'numberField_m0eohh4q' in item.form_data)#回款金额
    refund_amount_temp = float(statement_information[0][0].form_data.get('numberField_lzs6slk5_value',0))
    refund_amount_extra = refund_amount_temp if refund_amount_temp > 0 else refund_amount #收款余额
    ys_refund_amount = float(statement_information[0][0].form_data.get('numberField_lzs6sljt',0))#应收金额
    invoice_amount = statement_information[0][0].form_data.get('numberField_lzs6sljy',0)#开票金额
    wkp_refund_amount = ys_refund_amount-invoice_amount#未开票
    for item in sorted_project_result:
        commission_id_temp = item.form_data.get('textField_lzs0x0b9',0)
        invoice_amount_due = invoice_amount - refund_amount #已开票欠款
        yida_client.update_form_data_by_field(
                "FORM-2E26102393E0493BA3EC8F1753C3911EYXYD",
                admin_user_id,
                [{
                    "type": "TEXT",
                    "operator": "eq",
                    "componentName": "TextField",
                    "key": "textField_m0eljcmb",
                    "value": project_id
                }],
                {
                    "numberField_lzs6slk4": refund_amount,
                    "numberField_lzs6slk8": wkp_refund_amount,
                    "numberField_lzs6slk5": refund_amount_extra,
                    "numberField_lzs7hqne": invoice_amount_due
                 }  
            )
        refund_amount_extra -= item.form_data['numberField_m09lw3i6']
        if refund_amount_extra >= 0 :  
            yida_client.update_form_data_by_field(
                "FORM-2E26102393E0493BA3EC8F1753C3911EYXYD",
                admin_user_id,
                [{
                    "type": "TEXT",
                    "operator": "eq",
                    "componentName": "TextField",
                    "key": "textField_m0eljcmb",
                    "value": project_id
                }],
                {      
                    "numberField_lzs6slk5": refund_amount_extra ,       
                 }  
            )
            yida_client.update_form_data_by_field(
                "FORM-38C305CFD3D14A8B99984C59FE48E537J8SW",
                admin_user_id,
                [{
                    "type": "TEXT",
                    "operator": "eq",
                    "componentName": "TextField",
                    "key": "textField_m0am6qv4",
                    "value": commission_id_temp
                }],
                {
                    "selectField_m0dijv87": "已结清" 
                 }
            )
    return ApiResponse.success("数据更新成功")

@csrf_exempt
@require_http_methods(["GET"])
def calc_commission_amount(request):
    commission_id = request.GET.get("commission_id")
    results,total = yida_client.get_all_form_data_by_search_field("FORM-2031FFBD99D1442AA606BB665B218400TTVG",
                                                  admin_user_id,
                                                  search_field=[
                                                        {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_lzwdkwlk",
                                                            "value": commission_id
                                                        }
                                                    ])
    total_amount = sum(item.form_data['numberField_m0dj9ha5'] for item in results if 'numberField_m0dj9ha5' in item.form_data)
    
    try:
        response = yida_client.update_form_data_by_field(
            "FORM-38C305CFD3D14A8B99984C59FE48E537J8SW",
            admin_user_id,
            [{
                "type": "TEXT",
                "operator": "eq",
                "componentName": "TextField",
                "key": "textField_lzs0x0b9",
                "value": commission_id
            }],
            {"numberField_m09lw3i6": total_amount }  
        )
        if response == "success":
            return ApiResponse.success(response)
        else:
            return ApiResponse.fail(response,400)
    except Exception as e:
        print(e)
        return ApiResponse.fail("更新失败",400)
    
    

# 使用宜搭数据在平台创建工程并生成二维码去创建委托
@csrf_exempt
@require_http_methods(["GET"])
def get_uuid_QRcode_by_project(request):
    formInstId = request.GET.get('formInstId')
    form_uuid = 'FORM-BD41952201D4490A804B013A18E98A5CQYKA'
    yida_instance = yida_client.get_form_items_by_ids(form_uuid, formInstId, admin_user_id)
    
    body = {
        "project_number": yida_instance[0].form_data["textField_m1nbexlw"],  # 项目编号
        "registration_date": yida_instance[0].form_data["dateField_lzrzlfjq"],  # 登记日期
        "project_name": yida_instance[0].form_data["textField_lzrzlfjr"],  # 项目名称
        "project_address": yida_instance[0].form_data["textareaField_lzxvw0ez"],  # 项目地址
        # 委托单位
        "entrusting_unit":yida_instance[0].form_data["textField_lzrzlfk6"],   #单位名称
        "entrusting_contact":yida_instance[0].form_data["textField_lzrzlfkb"],   #联系人
        "entrusting_phone":yida_instance[0].form_data["textField_lzrzlfkf"],   #电话
        # 建设单位
        "construction_unit":yida_instance[0].form_data["textField_lzrzlfk7"],   #单位名称
        "construction_contact":yida_instance[0].form_data["textField_lzrzlfkc"],   #联系人
        "construction_phone":yida_instance[0].form_data["textField_lzrzlfkg"],   #电话
        # 施工单位
        "contractor_unit":yida_instance[0].form_data["textField_lzrzlfk8"],   #单位名称
        "contractor_contact":yida_instance[0].form_data["textField_lzrzlfkd"],   #联系人
        "contractor_phone":yida_instance[0].form_data["textField_lzrzlfkh"],   #电话
        # 监理单位
        "supervisory_unit":yida_instance[0].form_data["textField_lzxw8qhi"],   #单位名称
        "supervisory_contact":yida_instance[0].form_data["textField_lzrzlfke"],   #联系人
        "supervisory_phone":yida_instance[0].form_data["textField_lzrzlfki"],   #电话
        "callback_url": "linanzjz"
    }
    print('body-->', body)
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()
    response = xm_client.create_project(body)
    
    if response.get('code') == 200:
        project_token = response.get('data').get('project_token')
        print('project_token--->',project_token)
        qr_url = f'http://report.zjxmyq.cn/commission/create?uuid={project_token}'
        # Generate QR code
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(qr_url)
        qr.make(fit=True)
        img = qr.make_image(fill='black', back_color='white')
        # Convert image to base64
        buffered = BytesIO()
        img.save(buffered, format="PNG")
        img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
        
        # Pass base64 image to template
        context = {
            'qrcode': f"data:image/png;base64,{img_base64}",
            'url': qr_url,
            "company_name":"杭州临安城市工程质量检测有限公司"
        }
        return render(request, 'qrcode_by_project.html', context)
    else:
        return ApiResponse.fail('失败')

# 在宜搭中创建委托   
@csrf_exempt
@require_http_methods(["POST"])
def create_commission_yida(request):
    req_data = json.loads(request.body)
    commision_info = req_data.get('commision_info')
    # 工程数据
    project_data = yida_client.get_form_data_by_search_field(
        'FORM-BD41952201D4490A804B013A18E98A5CQYKA',
        admin_user_id,
        {
            "textField_lzrzlfjr":req_data.get("project_name")
        }
    )
    xm_client = XmCloudClient()
    print('1111--->',req_data.get("detection_project_id"))
    exam_data = xm_client.get_xm_exam_item_detail(req_data.get("detection_project_id"))
    print('exam_data--->',exam_data)
    if exam_data.get('code') == 200:
        contracts_code = exam_data.get('data').get('commision_code')
        print('commision_code--->', contracts_code)
        match_field_data = {
          "textField_lzxv9z4j": contracts_code,
        }
        # 流水号
        serial_number = gen_serial_number(
            'FORM-38C305CFD3D14A8B99984C59FE48E537J8SW',
            match_field_data,
            'numberField_lzxv9z4i'
        )
        print('流水号--->',serial_number)
        # contracts_report = contracts_code +'-'+ str(datetime.now().year) +'-' + f"{serial_number:05}"
        contracts_report = contracts_code +'-'+ str(datetime.now().year) +'-'
        print('委托编号--->',contracts_report)
    # return
    
    # 资质类别
    label = req_data.get("qualification_name")
    print('资质类别--->', label)
    yida_client.create_form_data(
        'FORM-38C305CFD3D14A8B99984C59FE48E537J8SW',
        admin_user_id,
        {
            "associationFormField_lzs0x0am":[
              {
                "appType": 'APP_Z006W6F6CE9REPXVWPH6', 
                "formType": 'receipt',
                "formUuid": 'FORM-BD41952201D4490A804B013A18E98A5CQYKA',
                "instanceId": project_data[0].form_instance_id,
                "title": project_data[0].form_data["textField_lzrzlfjr"],
              },  
            ],
            "textField_lzuvzaex": project_data[0].form_data["textField_lzrzlfjr"],  #项目名称 
            "textField_m0am6qv4": project_data[0].form_data["textField_m1nbexlw"],  #项目编号
            "selectField_m0emrkj8": label,  #资质类别
            "selectField_m0dj9ha7": req_data.get("exam_name")[0],  #检测大类
            "selectField_m0dj9ha3":req_data.get("detection_project_id"),  #检测项目
            "textField_lzxv9z4j": contracts_code,  #委托代码
            "numberField_lzxv9z4i": serial_number,  #委托流水号
            "textField_lzs0x0b9": contracts_report,  #委托编号
            "employeeField_lzs0x0b4": ["300208014636253254"],  #编制人  
            "radioField_m025klsq": "见证取样",
            "selectField_lzwfu6pg": "单份",
        }
    )
    # 查询委托数据
    commission_data = yida_client.get_form_data_by_search_field(
        'FORM-38C305CFD3D14A8B99984C59FE48E537J8SW',
        admin_user_id,
        {
            "textField_lzs0x0b9":contracts_report
        }
    )
    # print('commission_data--->',commission_data[0].form_instance_id)
    for index, sample in enumerate(commision_info):
        # 检测参数列表
        tableDataList = []
        checkboxData = []
        for item in sample['tableData']:
            checkboxData.append(item["name"])
            tableData = {}
            tableData["textField_m0emrkj4"] = item["name"]  # 参数名称
            tableData["textField_m0emrkjb"] = item["id"]  # uid
            tableDataList.append(tableData)
        print('tableDataList--->',tableDataList)
        # print('------>',sample['sampleParameters'].get("production_date"))
        # time_str = sample['sampleParameters'].get("production_date")
        # # 使用 isoparse 自动解析时间字符串
        # production_date = parser.isoparse(time_str)
        # print("production_date---->",production_date)
        # # 如果需要将其转化为毫秒级别的时间戳
        # timestamp_ms = int(production_date.timestamp() * 1000)
        # production_date_ms = int(production_date.timestamp() * 1000)
        yida_client.create_form_data(
            'FORM-2031FFBD99D1442AA606BB665B218400TTVG',
            admin_user_id,
            {
                "associationFormField_lzuvjinv":[
                  {
                    "appType": 'APP_Z006W6F6CE9REPXVWPH6', 
                    "formType": 'receipt',
                    "formUuid": 'FORM-855DADF456844DFB97682B3B85C83212CRGP',
                    "instanceId": commission_data[0].form_instance_id,
                    "title": commission_data[0].form_data["textField_lzuvzaex"],
                  },  
                ],
                "tableField_m0emrkj5": tableDataList,  #检测参数
                "textField_lzwdkwlk":contracts_report,  #委托编号
                "textField_m0g5ssx7":contracts_report+'-'+str(index+1),  #样品编号
                "selectField_m0emrkj8":label,  #资质类别
                "selectField_m0dj9ha7":req_data.get("exam_name")[0],  #检测大类
                "selectField_m0dj9ha3":req_data.get("exam_name")[1],  #检测项目
                "checkboxField_m0emrkj2":checkboxData,  #检测参数
                # "selectField_m0kma0fj":sample['sampleParameters'].get("sample_spec"),  #规格
                # "textField_m0kma0fq":sample['sampleParameters'].get("sample_name"),  #样品名称
                # "textField_m0kma0fr":sample['sampleParameters'].get("sample_status"),  #样品状态
                # # "dateField_m0kma0fv":production_date_ms,  #生产日期
                # "textField_m0kma0fu":sample['sampleParameters'].get("production_manufacturer"),  #生产厂家
                # "numberField_m0kma0g6":sample['sampleParameters'].get("sample_count"),  #样品数量
                # "textField_m0kma0gn":sample['sampleParameters'].get("pledge_number"),  #质保单号
                # "textField_m0kma0g8":sample['sampleParameters'].get("position"),  #结构部位
                # "numberField_m0kma0gf":sample['sampleParameters'].get("representative_count"),  #代表数量
                # "textField_m0kma0ge":sample['sampleParameters'].get("engineering_site"),  #工程部位
            }
        )
    return ApiResponse.success(data=contracts_report, message='成功')

def gen_serial_number(form_uuid,match_field_data,sn_field):
    try:
        if isinstance(match_field_data,list):
            match_field_data = match_field_data + [{"key":sn_field,"value":"","type":"DOUBLE","operator":"is_not","componentName":"NumberField"}]
        result = yida_client.get_form_data_by_search_field(form_uuid=form_uuid,
                                                  userId=admin_user_id,
                                                  search_field=match_field_data,
                                                  page_size=5,
                                                  dynamic_order={sn_field:"-"})
        if result:
            serial_number = result[0].form_data.get(sn_field,0)+1
            return serial_number
        elif len(result) == 0:
            return 1
    except Exception as err:
        return 0
      
    
@csrf_exempt
@require_http_methods(["GET"])
def test_sql(request):
    db_tool = DBTool("linanzjz_db",True)
    # print(f"The db_tool_instance is {db_tool}")
    # rows = db_tool.execute_query("SELECT * FROM tb_person")
    # for row in rows:
    #     print(row)  # 这将打印出每一行的内容
    #     pass
    import pymssql
    # 连接 SQL Server
    conn = pymssql.connect(server='192.168.1.39', port=1433, user='sa', password='xtd**)^', database='test_db')

    # 创建游标
    cursor = conn.cursor()

    # 执行查询
    cursor.execute('SELECT * FROM tb_person')

    # 获取查询结果
    rows = cursor.fetchall()

    # 打印结果
    for row in rows:
        print(row)

    # 关闭连接
    conn.close()


@csrf_exempt
@require_http_methods(["GET"])
def print_order(request):
    form_inst_id = request.GET.get("form_inst_id")
    commission_result = yida_client.get_form_items_by_ids("FORM-38C305CFD3D14A8B99984C59FE48E537J8SW",
                                                            form_inst_id,
                                                            admin_user_id,
                                                            )
    commission_form = commission_result[0].form_data
    if not commission_form.get("selectField_m0dj9ha3_id"):
        return ApiResponse.fail(message="未找到检测项目，请检查")
    commission_id = commission_form.get("textField_lzs0x0b9")
    sample_result = yida_client.get_form_data_by_search_field("FORM-2031FFBD99D1442AA606BB665B218400TTVG",
                                                                    admin_user_id,
                                                                    search_field=[
                                                                        {
                                                                            "type": "TEXT ",
                                                                            "operator": "eq",
                                                                            "componentName": "TextField ",
                                                                            "key": "textField_lzwdkwlk",
                                                                            "value": commission_id
                                                                        }
                                                                    ])
    sample_result_extra = []
    if sample_result:
        sample_form:dict = sample_result[0].form_data#样品组表单
        sample_result_extra = sample_form.get("multiSelectField_m17ibo5s",[])
    public_render_data = {
        "报告编号":commission_form.get("textField_lzs0x0b9"),
        "工程名称":commission_form.get("textField_lzuvzaex"),
        "检测项目":commission_form.get("selectField_m0dj9ha3"),
        "委托人":commission_form.get("textField_lzxv9z4b"),
        "委托编号":commission_form.get("textField_lzs0x0b9"),
        "委托单位":commission_form.get("textField_lzs0x0ba"),
        "委托日期":commission_form.get("dateField_lzweua3h"),
    }
    public_render_data_item = ["报告编号","工程名称","检测项目","委托人","委托编号","委托单位","委托日期","送检日期","检测类别","生产厂家",
                              "备注","建设单位","委托单位","见证人","样品状态","见证单位","施工单位"
                              ]
    private_render_data = {}
    key_count = defaultdict(int)
    for item in sample_result_extra:
        if '##' in item:
            key, value = item.split('##') 
            if key in public_render_data:
                if key not in public_render_data_item:
                    key_count[key] += 1  # 记录出现次数
                    new_key = f"{key}_{key_count[key]}"  
                    private_render_data[new_key] = value  
            else:
                private_render_data[key] = value
    render_data = {**private_render_data, **public_render_data}  
    print(render_data)
    xm_client = XmCloudClient()
    model_details = xm_client.get_xm_exam_item_detail(commission_form.get("selectField_m0dj9ha3_id"))
    # print(model_details)
    model_id_resource = model_details["data"]["order_form_model_id"]
    if not model_id_resource:
        return ApiResponse.fail("该检测项目未配置报告模板")
    create_order_result = xm_client.render_model(model_id = model_id_resource,
                                           render_data=render_data)
    print_data = create_order_result.get("data")
    print_url = print_data.get("download_url")
    if create_order_result.get("code") == 200:
        if print_url:
            return redirect(print_url)
        return ApiResponse.fail("No redirect URL found in the response")
    else:
        return ApiResponse.fail(create_order_result.get("message"))
@csrf_exempt
@require_http_methods(["GET"])
def print_cost_sheet(request):
    '''打印检测项目费用统计表'''
    model_id = 451
    start = request.GET.get("start")
    end = request.GET.get("end")
    if start:
        start = timestamp_to_yida_date(start)
    if not end:
        search_end = timestamp_to_yida_date((datetime.now().timestamp()+ 60 * 60 * 24)*1000)
        end = timestamp_to_yida_date(datetime.now().timestamp() * 1000)
    else:
        search_end = timestamp_to_yida_date(end+1000 * 60 * 60 * 24)
        end = timestamp_to_yida_date(end)
    
    project_id = request.GET.get("project_id")
    render_data = {
        "工程名称":"",
        "统计时间": f"{start}到{end}",
        "统计内容":[]
    }
    yida_res,total = yida_client.get_all_form_data_by_search_field("FORM-38C305CFD3D14A8B99984C59FE48E537J8SW",
                                                  admin_user_id,
                                                  [
                                                      {
                                                          "type": "TEXT ",
                                                          "operator": "eq",
                                                          "componentName": "TextField ",
                                                          "key": "textField_m0am6qv4",
                                                          "value": project_id
                                                      }
                                                  ],start,search_end)
    if yida_res and total >0:
        cost_data = []
        for item in yida_res:
            form_data = item.form_data
            if not render_data.get("工程名称") and form_data.get("textField_lzuvzaex"):
                render_data["工程名称"] = form_data.get("textField_lzuvzaex")
            detection_project = form_data.get("selectField_m0dj9ha3")
            amount = form_data.get("numberField_m09lw3i6",0)
            cost_data.append({
                "key": detection_project,
                "amount": amount
            })
        merged_dict = {}
        # 遍历字典数组
        for item in cost_data:
            key = item["key"]
            amount = item["amount"]
            # 如果 key 已存在，更新总金额和数量
            if key in merged_dict:
                merged_dict[key]["total_amount"] += amount
                merged_dict[key]["count"] += 1
            else:
                # 如果 key 不存在，初始化
                merged_dict[key] = {"total_amount": amount, "count": 1}

        # 将结果转换为列表格式
        render_data["统计内容"] = [{"检测项目": k, "小计": v["total_amount"], "数量": v["count"]} for k, v in merged_dict.items()]
    result = xm_client.render_model_xlsx(model_id,render_data)
    if result.get("code") == 200:
        render_result = result.get("data")
        return redirect(render_result.get("download_url"))
